package zookeeper;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;



public class ConnectMySql {
    DruidDataSource dataSource = null;

    public void setDataSource(Configuration configuration) {
        dataSource = new DruidDataSource();
        dataSource.setDriverClassName(configuration.getDriverClassName());
        dataSource.setUrl(configuration.getUrl());
        dataSource.setUsername(configuration.getUsername());
        dataSource.setPassword(configuration.getPassword());
        dataSource.setInitialSize(Integer.parseInt(configuration.getInitialSize()));
        dataSource.setMaxActive(Integer.parseInt(configuration.getMaxActive()));
        dataSource.setMaxWait(Integer.parseInt(configuration.getMaxWait()));
    }


    public void showTables(Configuration configuration){
        setDataSource(configuration);
        QueryRunner qr = new QueryRunner(dataSource);
        String sql = "show tables;";
        List<Object[]> result = null;
        try {
            result = qr.query(sql, new ArrayListHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        for (Object[] o : result){
            System.out.println(Arrays.toString(o));
        }

    }

    public static void main(String[] args) {
        final ConnectMySql connectMySql = new ConnectMySql();
        ZkClient zk = new ZkClient("linux100:2181,linux101:2181,linux102:2181");
        zk.setZkSerializer(new ZkConfSerializer());
        // 读取zookeeper节点内的数据
        Configuration configuration = zk.readData("/mysql-configuration");

        //获取连接并打印当前数据库内的表
        connectMySql.showTables(configuration);

        zk.subscribeDataChanges("/mysql-configuration", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                Configuration newConfiguration = (Configuration) o;
                connectMySql.dataSource.close();
                connectMySql.showTables(newConfiguration);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("配置中心节点被删除");
            }
        });

        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
